Get any type from an array

I have an array that can contain string and int values mixed. There are columns with string values and other columns with int values.

How can I read this array in a loop? I cannot use casting, because I don't know what type to cast. I would like to get every values as string to be able to print them. Can anyone help me? Thanx.


GaborMoizes - Tue Jul 29 11:15:06 EDT 2014

Re: Get any type from an array
Mathias Mamsch - Tue Jul 29 12:49:30 EDT 2014

So first of all, when you read the value from an array, you must know the type. There is no way around that. Anything else will give you nasty crashes. Ok, so far so good. If you know which column in the array has integer values then you need to have two reads:

string value = ""; 

if (isIntegerColumn(column)) {
    int val = (get(arr, row, column) int);
    value = val "";
} else {
    string val = (get(arr, row, column) string);
    value = val; 
}

print "String Value: " value "\n"

If you do not have this information about the columns, then you need to alter the way you put values to your array. I would think the easiest thing to do would be to find all places, where you put integers into your array and then change them to put strings in.

...
int val = ...
...
// put (arr, val, i,j)   // instead of this we do
put (arr, val "", i, j)  // use a string 

This way, you know how to read the elements of the array. Another approach (although much to complicated would be to simply remember the type of each column in a skip list) and use the information to read the right type back.

Regards, Mathias

Re: Get any type from an array
Doug.Zawacki - Tue Jul 29 15:28:47 EDT 2014

You could always store everything as a string and cast to an integer for the values that need it.

Re: Get any type from an array
GaborMoizes - Wed Jul 30 02:14:06 EDT 2014

Thank you Mathias and Doug, both approach makes sense. I try to figure out which one is better for my case.